﻿using System;
using System.Collections.Generic;
using Affinity.Core.Validation;

namespace Affinity.Flux
{
    /// <summary>
    /// Thread-safe collection of TypeInfo objects.
    /// </summary>
    internal class TypeInfoCollection
    {
        /// <summary>
        /// Gets or creates a TypeInfo for the specified type.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public TypeInfo GetOrCreateTypeInfo(Type type)
        {
            Assert.ArgumentNotNull(type, "type");

            lock (_typeInfoCacheLock)
            {
                TypeInfo typeInfo;

                if (!_typeInfoCache.TryGetValue(type, out typeInfo))
                {
                    typeInfo = TypeInfo.Create(type);
                    _typeInfoCache[type] = typeInfo;
                }

                return typeInfo;
            }
        }

        private readonly Dictionary<Type, TypeInfo> _typeInfoCache = new Dictionary<Type, TypeInfo>();
        private readonly object _typeInfoCacheLock = new object();
    }
}
